﻿

#include "Core/LevelExit.h"

#include "PaperFlipbookComponent.h"
#include "Components/BoxComponent.h"
#include "Core/PJGameInstance.h"
#include "Core/PlayerZDCharacter.h"
#include "Kismet/GameplayStatics.h"


ALevelExit::ALevelExit()
{
	PrimaryActorTick.bCanEverTick = true;
	
	BoxComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComponent"));
	SetRootComponent(BoxComponent);

	FlipbookComponent = CreateDefaultSubobject<UPaperFlipbookComponent>(TEXT("FlipBookComponent"));
	FlipbookComponent->SetupAttachment(RootComponent);

	FlipbookComponent->SetPlayRate(0.0f);
	FlipbookComponent->SetLooping(false);
}

void ALevelExit::BeginPlay()
{
	Super::BeginPlay();

	BoxComponent->OnComponentBeginOverlap.AddDynamic(this, &ALevelExit::OverlapBegin);
}

void ALevelExit::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

void ALevelExit::OverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
	UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	APlayerZDCharacter* Player = Cast<APlayerZDCharacter>(OtherActor);
	if (Player && Player->IsAlive)
	{
		Player->Deactivate();
		
		IsActive = false;

		FlipbookComponent->SetPlayRate(1.0f);
		FlipbookComponent->PlayFromStart();

		UGameplayStatics::PlaySound2D(GetWorld(), PlayerEnterSound);
		GetWorldTimerManager().SetTimer(WaitTimer, this, &ALevelExit::OnWaitTimerTimeout, 1.0f, false, WaitTimeInSeconds);
	}
}

void ALevelExit::OnWaitTimerTimeout()
{
	UPJGameInstance* MyGameInstance = Cast<UPJGameInstance>(GetGameInstance());
	if (MyGameInstance)
	{
		MyGameInstance->ChangeLevel(LevelIndex);
	}
}

